/*
启动一个wechaty robot与Contact通信
*/

const ContactName = 'Cecile'  // 联系人昵称（非备注名）
const port = 8081

const {
    Contact,
    log,
    Message,
    // ScanStatus,
    WechatyBuilder,
    // UrlLink,
    // MiniProgram,
    MessageType
} = require("wechaty");

const {
    PuppetXp
} = require('wechaty-puppet-xp')

const name = 'wechat-puppet-xp';
const puppet = new PuppetXp()

const bot = WechatyBuilder.build({
    name,
    puppet,
});

bot
    .on("login", (user) => {
        log.info("Robot", `${user} login`);
    })
    .on("logout", (user, reason) => {
        log.info("Robot", `${user} logout, reason: ${reason}`);
    })
    .on('error', (e) => { console.error(e) })
    .on("message", async (message) => {

        if (message.self()) {
            log.info('Robot got a message from itself!');
            return
        }

        if (message.type() === bot.Message.Type.Text) {
            const contact = message.talker() // 发消息人
            const content = message.text().trim() // 消息内容
            const alias = await contact.alias(); // 发消息人备注
            log.info(`发消息人: ${alias} 消息内容: ${content}`);

            if (contact == ContactName) {
                log.info('Robot got a message from friends!');
            }
        }
    })

bot
    .start()
    .then(() => log.info("Robot", "started."))
    .catch(err => console.error(err))

/*
REST API接受盘中监控工具发来的消息并转发给Contact
*/

var express = require('express');
var app = express();

app.use(express.urlencoded({ extended: false }))
app.use(express.json())

app.get('/msg', async (req, res) => {
    // send message: test
    let contact = await bot.Contact.find({ name: ContactName })
    let str = 'Test message'
    await contact.say(str) // 发送消息

    log.info('Robot recieved a Get message.')
    res.send('hello')

})

app.post('/msg', async (req, res) => {
    // forward message

    let body = req.body

    let contact = await bot.Contact.find({ name: ContactName })
    await contact.say(body.message)

    log.info('Robot received a Post message.')
    res.send(body)
})

var server = app.listen(port, function () {

    var host = server.address().address
    var port = server.address().port

    log.info("Wechat Robot starts： http://%s:%s", host, port)

})